#include <stdio.h>
#include <stdlib.h>

#include "jrm.h"

void error(const char *message);
char *read_file(const char *filename);

int main(int argc, char *argv[])
{
    char *input;
    int row_test, iter;
    float estimated, real;

    /* Verify argument */
    if (argc < 2)
        error("Missing input file.");

    /* Read and store input file */
    input = read_file(argv[1]);

    if (input == NULL)
        error("Invalid input file.");

    /* Initialize method using input */
    jrm_initialize(input);

    /* Execute and evaluate results */
    jrm_evaluate(&iter, &row_test, &estimated, &real);

    printf("%s\n%s: %d\n%s: %d => [%f] =? %f\n%s\n",
           "-------------------------------------------------------",
           "Iterations", iter,
           "RowTest", row_test, estimated, real,
           "-------------------------------------------------------"
          );

    /* Free memory */
    jrm_delete();
    free(input);

    return 0;
}

void error(const char *message)
{
    fprintf(stderr, "%s\n", message);
    exit(1);
}

char *read_file(const char *filename)
{
    char *buffer;
    long size;
    FILE *fp;

    fp = fopen(filename, "r");
    if (fp == NULL)
        return NULL;

    fseek(fp, 0, SEEK_END);
    size = ftell(fp);
    rewind(fp);

    buffer = (char *) malloc(size * sizeof(char));

    fread(buffer, sizeof(char), size, fp);
    fclose(fp);

    return buffer;
}
